package tv.dyndns.kishibe.server.handwriting;

import org.apache.commons.pool.BasePoolableObjectFactory;

import com.google.inject.Inject;
import com.sun.jna.Pointer;

public class ZinniaObjectFactory extends BasePoolableObjectFactory<Pointer> {
	private static final String MODEL_FILE_PATH = "/var/www/qmaclone/handwriting-ja.model";
	private final ZinniaLibrary zinnia;

	@Inject
	public ZinniaObjectFactory(ZinniaLibrary zinnia) {
		this.zinnia = zinnia;
	}

	@Override
	public Pointer makeObject() throws Exception {
		Pointer recognizer = zinnia.zinnia_recognizer_new();

		if (zinnia.zinnia_recognizer_open(recognizer, MODEL_FILE_PATH) == 0) {
			System.err.printf("ERROR: %s\n", zinnia.zinnia_recognizer_strerror(recognizer));
			zinnia.zinnia_recognizer_destroy(recognizer);
			throw new Exception("zinnia 辞書ファイルの読み込みに失敗しました");
		}

		return recognizer;
	}

	@Override
	public void destroyObject(Pointer obj) throws Exception {
		Pointer recognizer = (Pointer) obj;
		zinnia.zinnia_recognizer_destroy(recognizer);
	}
}
